package com.jasonchoi.security.commons.security.authorization;

import com.jasonchoi.security.entity.Permission;
import com.jasonchoi.security.entity.Role;
import com.jasonchoi.security.repository.PermissionRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 从数据库中获取url对应的role信息
 */
@Log4j2
@Service
public class UrlRolesFilterHandler implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private PermissionRepository permissionRepository;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        Permission permission = permissionRepository.findByPermission(requestUrl);
        log.debug("######UrlRolesFilterHandler --> requestUrl:" + requestUrl);
        if (Objects.isNull(permission)) {
            //公共权限不拦截
            return null;
        }
        List<Role> roleList = permission.getRoleList();
        String[] roleNames = new String[roleList.size()];
        for (int i = 0; i < roleList.size(); i++) {
            roleNames[i] = roleList.get(0).getName();
        }
        return SecurityConfig.createList(roleNames);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }

}
